package com.cos.hospital.tool;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Rect;
import android.location.LocationManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.cos.hospital.R;
import com.cos.hospital.ui.login.LoginActivity;
import com.jude.utils.JActivityManager;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author YBY
 * @description 常用工具方法类
 */
public class MyUtil {
    private volatile static MyUtil instance;

    private MyUtil() {
    }

    public static MyUtil getInstance() {
        if (instance == null) {
            synchronized (MyUtil.class) {
                if (instance == null) {
                    instance = new MyUtil();
                }
            }
        }
        return instance;
    }

    /**
     * 禁止Edittext弹出软件盘，光标依然正常显示。
     */
    public void disableShowSoftInput(EditText editText) {
        Class<EditText> cls = EditText.class;
        Method method;
        try {
            method = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
            method.setAccessible(true);
            method.invoke(editText, false);
        } catch (Exception e) {
            ULog.d(e.toString());
        }
    }

    public void closeInputMethod(Activity act) {
        InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
        //得到InputMethodManager的实例
        if (isSoftShowing(act)) {//如果开启
            if (imm != null) {
                //关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
                imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    private boolean isSoftShowing(Activity act) {
        //获取当前屏幕内容的高度
        int screenHeight = act.getWindow().getDecorView().getHeight();
        //获取View可见区域的bottom
        Rect rect = new Rect();
        act.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        return screenHeight - rect.bottom > 160;
    }

    /**
     * 判断 用户是否安装啦啦兑
     */
    public boolean isLLDAvilible(Context context) {
        PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.jwbc.cn")) {
                    return true;
                }
            }
        }
        return false;
    }

    public String getCompleteUrl(String text) {
        Pattern p = Pattern.compile("((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\" +
            ".[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?", Pattern.CASE_INSENSITIVE);
        Matcher matcher = p.matcher(text);
        boolean b = matcher.find();
        if (b) {
            return matcher.group();
        } else {
            return null;
        }
    }

    public void removeAuthor(Context context) {
        SPUtil.clearUserInfo();
        new JActivityManager().closeAllActivity();
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    public int getTotalPageCount(int pageSize, int recordCount) {
        if (recordCount % pageSize == 0) {
            return recordCount / pageSize;
        } else {
            return recordCount / pageSize + 1;
        }
    }

    //获取版本号
    public String getMobileSystem() {
        return "Android " + android.os.Build.VERSION.RELEASE;
    }

    //获取手机型号
    public String getMobileBrand() {
        return android.os.Build.MODEL;
    }

    //获取MD5
    public String getContentMD5(String info) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(info.getBytes("UTF-8"));
            byte[] encryption = md5.digest();
            StringBuilder strBuf = new StringBuilder();
            for (byte anEncryption : encryption) {
                if (Integer.toHexString(0xff & anEncryption).length() == 1) {
                    strBuf.append("0").append(Integer.toHexString(0xff & anEncryption));
                } else {
                    strBuf.append(Integer.toHexString(0xff & anEncryption));
                }
            }
            return strBuf.toString();
        } catch (NoSuchAlgorithmException e) {
            return "";
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    /**
     * 检测GPS是否打开
     */
    public boolean checkGPSIsOpen(Context context) {
        boolean isOpen = false;
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager != null) {
            isOpen = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        }
        return isOpen;
    }

    /**
     * 显示拒绝授权后的弹窗
     */
    public void toSetting(Context context, String s, int end, boolean finish) {
        try {
            SpannableStringBuilder builder = new SpannableStringBuilder(s);
            builder.setSpan(new ForegroundColorSpan(Color.BLACK), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.green_bg)), 6, end, Spannable
                .SPAN_EXCLUSIVE_EXCLUSIVE);
            builder.setSpan(new ForegroundColorSpan(Color.BLACK), end + 1, s.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            new AlertDialog.Builder(context, R.style.BDAlertDialog)
                .setCancelable(false)
                .setTitle("权限申请")
                .setMessage(builder)
                .setNegativeButton("取消", (dialogInterface, i) -> {
                    if (finish) {
                        ((Activity) context).finish();
                    }
                })
                .setPositiveButton("去授权", (dialogInterface, i) -> {
                    Uri packageURI = Uri.parse("package:" + context.getPackageName());
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                        packageURI);
                    context.startActivity(intent);
                    if (finish) {
                        ((Activity) context).finish();
                    }
                })
                .show();
        } catch (Exception e) {//暴力做法，避免上下文被回收后导致奔溃
            e.printStackTrace();
        }
    }

    public int getEnterCount(String str) {
        String regEx = "\n";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        int count = 0;
        while (m.find()) {
            count++;
        }
        return count;
    }

    public void openGaode(Context context, double latitude, double longitude, String address) {
        try {
            if (isInstallByread("com.autonavi.minimap")) {
                Intent intent = new Intent("android.intent.action.VIEW",
                    Uri.parse(
                        "androidamap://route?sourceApplication=应用名称" + "&dlat=" + latitude//终点的经度
                            + "&dlon=" + longitude//终点的纬度
                            + "&dname=" + address
                            + "&dev=0" + "&t=1"));
                context.startActivity(intent);
            } else {
                UToast.toast("没有安装高德地图客户端，请先下载该地图应用");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }

}